<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, FormInstance, FormRules, UploadProps } from 'element-plus';
import useStore from '@/store';
import { props } from './form';
defineOptions({ name: 'EmployeeForm' });
const _props = defineProps(props);
const save = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      window.$api.employee.save(form).then(res => {
        ElMessage.success('保存成功!');
        useStore.window.windowRemove('EmployeeForm' + (form.id ?? ''));
      });
    }
  });
};
const imageUrl = ref('');
const organizations = ref([]);
const users = ref([]);
const educations = ref([]);
const employeeStatuss = ref([]);
const treeRef = ref(null);
const ruleFormRef = ref<FormInstance>();
const form = reactive({
  id: null,
  organizationIds: [],
  userId: null,
  number: null,
  idCard: null,
  name: null,
  gender: null,
  marriage: null,
  education: null,
  mobilePhone: null,
  email: null,
  address: null,
  hireDate: null,
  termDate: null,
  status: null,
  avatar: null,
  remark: null,
  attachmentId: null,
});
const rules = reactive<FormRules>({
  organizationIds: [{ required: true, message: '请选择所属组织机构', trigger: 'change' }],
  number: [
    { required: true, message: '请输入员工编号', trigger: 'blur' },
    { max: 50, message: '不能多于50个字符', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { max: 50, message: '不能多于50个字符', trigger: 'blur' },
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { max: 50, message: '不能多于50个字符', trigger: 'blur' },
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  marriage: [{ required: true, message: '请选择婚姻', trigger: 'change' }],
  education: [{ required: true, message: '请选择学历', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  mobilePhone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { max: 50, message: '不能多于50个字符', trigger: 'blur' },
  ],
});
/** 加载基础数据,字典等 */
const init = async () => {
  educations.value = useStore.dictionary.getComboBoxItems('education');
  employeeStatuss.value = useStore.dictionary.getComboBoxItems('employeestatus');
  await window.$api.organization.query().then(res => {
    organizations.value = res.data;
  });
  await window.$api.user.getUsers().then(res => {
    users.value = res.data;
  });
};
const detail = () => {
  window.$api.employee.detail(_props.window.params.id).then(res => {
    form.id = res.data.id;
    form.userId = res.data.userId;
    form.organizationIds = res.data.organizationIds;
    form.number = res.data.number;
    form.idCard = res.data.idCard;
    form.name = res.data.name;
    form.gender = res.data.gender;
    form.marriage = res.data.marriage;
    form.education = res.data.education;
    form.mobilePhone = res.data.mobilePhone;
    form.email = res.data.email;
    form.address = res.data.address;
    form.hireDate = res.data.hireDate;
    form.termDate = res.data.termDate;
    form.status = res.data.status;
    form.avatar = res.data.avatar;
    form.remark = res.data.remark;
    imageUrl.value = res.data.attachmentPath;
  });
};
const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  //imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};
const beforeUpload: UploadProps['beforeUpload'] = rawFile => {
  const type = ['image/jpeg', 'image/jpg', 'image/png'];
  if (type.indexOf(rawFile.type) === -1) {
    ElMessage.error('上传的文件必须是JPG、JPEG、PNG三种之一!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!');
    return false;
  }
  return true;
};
const uploadAction = async option => {
  let params = new FormData();
  params.append('file', option.file);
  await window.$api.attachment.uploadEmployeePhoto(params).then(res => {
    form.attachmentId = res.data.attachmentId;
    imageUrl.value = res.data.attachmentPath;
  });
};
onMounted(() => {
  init();
  if (_props.window.params) {
    if (_props.window.params.id) {
      detail();
    }
  }
});
</script>

<template>
  <windows-window :window="window">
    <template #button>
      <windows-button-group size="18">
        <windows-button icon="fluent-save-28-regular" @click="save"></windows-button>
      </windows-button-group>
    </template>
    <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="100px" size="default" status-icon>
      <el-row>
        <el-col>
          <el-form-item label="关联用户" prop="userId">
            <el-select v-model="form.userId" clearable placeholder="Select">
              <el-option v-for="item in users" :key="item.id" :label="item.userName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="关联用户" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入用户账号" :disabled="form.userId ? true : false" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户密码" prop="password">
            <el-input v-model="form.password" placeholder="请输入员工密码" :disabled="form.userId ? true : false" />
          </el-form-item>
        </el-col> -->
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="所属机构" prop="organizationIds">
            <el-tree-select
              ref="treeRef"
              v-model="form.organizationIds"
              node-key="id"
              :data="organizations"
              :props="{
                children: 'children',
                label: 'name',
              }"
              multiple
              highlight-current
              default-expand-all
              check-strictly
            ></el-tree-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-row>
            <el-col>
              <el-form-item label="员工编号" prop="number">
                <el-input v-model="form.number" placeholder="请输入员工编号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="员工姓名" prop="name">
                <el-input v-model="form.name" placeholder="请输入员工姓名" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="身份证号" prop="idCard">
                <el-input v-model="form.idCard" placeholder="请输入身份证号" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="12">
          <el-form-item label="照片" prop="avatar">
            <el-upload class="avatar-uploader" :show-file-list="false" :on-success="handleSuccess" :before-upload="beforeUpload" :auto-upload="true" :http-request="uploadAction">
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio :label="true">男</el-radio>
              <el-radio :label="false">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="婚姻" prop="marriage">
            <el-radio-group v-model="form.marriage">
              <el-radio :label="false">未婚</el-radio>
              <el-radio :label="true">已婚</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="员工状态" prop="status">
            <el-select v-model="form.status" fit-input-width>
              <el-option v-for="item in employeeStatuss" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学历" prop="education">
            <el-select v-model="form.education">
              <el-option v-for="item in educations" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="mobilePhone">
            <el-input v-model="form.mobilePhone" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱地址" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="入职日期" prop="hireDate">
            <el-date-picker v-model="form.hireDate" type="datetime" placeholder="请选择入职日期" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="离职日期" prop="termDate">
            <el-date-picker v-model="form.termDate" type="datetime" placeholder="请选择离职日期" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="地址" prop="address">
            <el-input v-model="form.address" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </windows-window>
</template>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
</style>
<style scoped lang="scss">
#edit {
  height: 100%;
}
.el-form {
  margin: 30px 20px;
}
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
}
.custom-node {
  display: flex;
  align-items: center;
  span {
    margin-left: 5px;
  }
}
.select-icon {
  display: flex;
  align-items: baseline;
  flex-wrap: wrap;
  border: 1px solid #dcdfe6;
  border-radius: 5px;
  margin-top: 5px;
  background: #fff;
  width: 100%;
  height: 200px;
  overflow: auto;
  .el-image {
    margin: 10px;
    cursor: pointer;
    border-radius: 5px;
    padding: 5px;
    &:hover,
    &.active {
      background: #dcdfe6;
    }
  }
}
</style>
